<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import PersonAPI from "@/api/genealogy/person.api";
import D3FamilyTreeFour from "./components/D3FamilyTreeFour.vue";
const route = useRoute();
const treeData = ref(null);
const treeDataFour = ref(null);
const treeDataForNine = ref(null);
const loading = ref(false);
const personId = route?.params?.personId;
const type = route?.query?.type;
// 弹窗
const dialog = reactive({
  title: "新增成员",
  visible: false,
  type: 0
});

function handleNodeClick(nodeData, type) {
  console.log('Node clicked:', personId);
  // Add any node click handling logic here
  if (personId) {
    PersonAPI.getTreeData(personId).then((data) => {
      treeData.value = data;
    });
    console.log(treeData.value)
  }
}

function handleNodeClickFour(nodeData, type) {
  console.log('Node clicked:', personId);
  // Add any node click handling logic here
  if (personId) {
    PersonAPI.getTreeDataForFour(personId).then((data) => {
      treeDataFour.value = data;
    });
  }
}

function handleNodeClickNine(nodeData, type) {
  console.log('Node clicked:', personId);
  // Add any node click handling logic here
  if (personId) {
    PersonAPI.getTreeDataForNine(personId).then((data) => {
      treeDataForNine.value = data;
    });
  }
}
// 新增：计算节点的代数，考虑开基祖
// function calculateGeneration(node, generation, founderName) {
//   // 如果当前节点是开基祖，返回1
//   if (node.isFounder === 1) {
//     return {
//       generation: 1,
//       founderName: `${node.lastName || ''}`
//     };
//   }

//   // 从当前节点向上查找最近的开基祖
//   let currentNode = node;
//   let generation = 0; // 默认值改为0，表示没有代数
//   let foundFounder = false;
//   let founderDepth = 0;
//   let founderName = '';

//   while (currentNode.parent) {
//     currentNode = currentNode.parent;
//     // 如果找到开基祖，从开基祖重新计算代数
//     if (currentNode.isFounder === 1) {
//       founderDepth = currentNode.depth;
//       foundFounder = true;
//       founderName = `${currentNode.lastName || ''}`;
//       break;
//     }
//   }

//   // 如果找到了开基祖，返回相对于开基祖的代数
//   if (foundFounder) {
//     // 修正计算逻辑：开基祖是第1代，其子代是第2代，以此类推
//     return {
//       generation: node.depth - founderDepth + 1,
//       founderName: founderName
//     };
//   }

//   // 如果没有找到开基祖，返回0，表示没有代数
//   return { generation: 0 };
// }

onMounted(() => {
  if (personId) {
    loading.value = true;
    switch (type) {
      case 'four':
        PersonAPI.getTreeDataForFour(personId).then((data) => {
        treeDataFour.value = data;
        }).finally(() => {
          loading.value = false;
        });
        break;
      case 'nine':
        PersonAPI.getTreeDataForNine(personId).then((data) => {
        treeDataForNine.value = data;
        }).finally(() => {
          loading.value = false;
        });
        break;
      default:
        PersonAPI.getTreeData(personId).then((data) => {
          // 判断children数据，给子类添加世代信息
          function addGenerationInfo(node, generation = 1, nameKey = '') {
         
            if (node.isFounder) {
              nameKey = node.lastName || '';
              generation = 1; // 重置代数
            }
            node.generation = generation;
            node.nameKey = nameKey;

            if (node.children && node.children.length > 0) {
              node.children.forEach(child => addGenerationInfo(child, generation + 1, nameKey));
            }
          }

          if (data) {
            data.forEach(node => addGenerationInfo(node));
          }
          function addCenturyInfo(node, century = 1) {
            node.century = century; // 设置当前节点的century
            if (node.children && node.children.length > 0) {
              node.children.forEach(child => addCenturyInfo(child, century + 1)); // 递归处理子节点，century加1
            }
          }
          if (data) {
            data.forEach(node => addCenturyInfo(node)); // 遍历数据，处理每个节点
          }
          treeData.value = data;
        }).finally(() => {
          loading.value = false;
        });
        break;
    }
  }
});
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading">
      <D3FamilyTreeFour :current-user-id="personId" title="全族谱" v-model="treeData" v-if="type=='all'"  @node-click="handleNodeClick" />
      <D3FamilyTreeFour :current-user-id="personId" title="九族图谱" v-model="treeDataFour" v-if="type=='four'"  @node-click="handleNodeClickFour" />
      <D3FamilyTreeFour :current-user-id="personId" title="十八代图谱" v-model="treeDataForNine" v-if="type=='nine'"  @node-click="handleNodeClickNine" />
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.app-container {
  width: 100%;
  height: 100%;
  padding: 20px;
}
</style>
